package redis.inaction.spring.configuration;

import io.lettuce.core.ReadFrom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.inaction.spring.entity.City;
import redis.inaction.spring.ops.RedisRepositoryOps;
import redis.inaction.spring.ops.RedisTemplateOps;
import redis.inaction.spring.ops.SpringCacheOps;

@Slf4j
@Configuration
public class SpringRedisConfiguration {

    @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceClientCustomizer(){
        return builder -> builder.readFrom(ReadFrom.MASTER_PREFERRED);
    }

    @Bean
    public RedisTemplate<String, City> cityRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, City> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
//
        Jackson2JsonRedisSerializer<City> valSerializer = new Jackson2JsonRedisSerializer<>(City.class);
        template.setValueSerializer(valSerializer);
        template.setHashValueSerializer(valSerializer);
        return template;
    }

    @Bean
    public RedisTemplateOps redisTemplateOps(){
        return new RedisTemplateOps();
    }

    @Bean
    public RedisRepositoryOps redisRepositoryOps(){
        return new RedisRepositoryOps();
    }

    @Bean
    public SpringCacheOps springCacheOps(){
        return new SpringCacheOps();
    }
}
